package com.isprint.jslx.lcc.wechat.utils;

import com.isprint.jslx.lcc.wechat.model.call_back_message.WechartXmlMessage;
import com.jfinal.log.Log;
import com.thoughtworks.xstream.XStream;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Xstream的工具类,微信定制版
 *
 * @author HYL
 * @create 2017-07-16 上午10:09
 **/
public class XstreamUtils4Wechat {
    private static Log log=Log.getLog(XstreamUtils4Wechat.class);
    /**
     * 重新关联,把原来的字段首字母大写映射到xml的子节点
     * @param clazz
     * @param xStream
     * @return
     */
    public static XStream adliasFile2Upcase(Class clazz, XStream xStream){
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            xStream.aliasField(captureName(field.getName()),clazz,field.getName());
        }
        return xStream;
    }

    /**
     * 首字母大写
     * @param name
     * @return
     */
    public static String captureName(String name) {
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        return  name;

    }

    public static WechartXmlMessage getWechatSuccessMessage(HttpServletRequest request){
        WechartXmlMessage message=null;
        try {
            ServletInputStream inputStream = request.getInputStream();
            XStream xStream = new XStream();
            xStream.alias("xml",WechartXmlMessage.class);
            adliasFile2Upcase(WechartXmlMessage.class,xStream);
            message = (WechartXmlMessage) xStream.fromXML(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("从请求中获取微信回调消息异常:"+e.getStackTrace().toString());
        }
        return message;

    }





}
